
/**
** \file       exec_andor.c
**
** \brief      functions about readline are here
**
** \author     Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse, De Olivera
**             Guillaume and Nguyen Viet Dung
**
** \version    0.8
**
** \date       26 November 2010
**
*/

#include "read_my_line.h"
#include "prompt.h"
#include "../exec_cmdline.h"

static char     *aux1(char               **argv,
                      int                *k,
                      char               *tab_tmp,
                      int                *i)
{
  prompt(1, argv);

  while (*k != -1)
  {
    read(STDIN_FILENO, tab_tmp + (*k - 1) * 1024, 1024);

    while ((tab_tmp[*i] != '\0') && (*i < *k * 1024))
      ++(*i);

    if (*i == *k * 1024)
      tab_tmp = realloc(tab_tmp, ++(*k) * 1024);
    else
      *k = -1;
  }

  tab_tmp[*i + 1] = '\0';
  tab_tmp = realloc(tab_tmp, *i + 1);

  return (tab_tmp);
}

static char     *aux2(int                *k,
                      char               *tab_tmp,
                      int                *i)
{
  while (*k != -1)
  {
    read(STDIN_FILENO, tab_tmp + (*k - 1) * 1024, 1024);

    while (tab_tmp[*i] != '\0' && *i < *k * 1024)
      ++(*i);

    if (*i == *k * 1024)
      tab_tmp = realloc(tab_tmp, ++(*k) * 1024);
    else
      *k = -1;
  }

  tab_tmp[*i + 1] = '\0';
  tab_tmp = realloc(tab_tmp, *i + 1);

  for (int j = 0; j < *i + 1; ++j)
  {
    if (tab_tmp[j] == '\n' && (strlen(tab_tmp) - (j + 1)) != 0)
      tab_tmp[j] = ';';
  }

  return (tab_tmp);
}

static int      aux(char                *tab_tmp,
                    int                 i)
{
  free(tab_tmp);
  tab_tmp = NULL;

  return (i);
}

int             exec_readline(char      **argv,
                              s_cmd     *cmd,
                              char      **envp)
{
  char          *tab_tmp = NULL;
  int           i = 0;
  int           k = 1;

  tab_tmp = calloc(1, 1024 * sizeof (char));

  if (isatty(STDIN_FILENO) == 1)
  {
    tab_tmp = aux1(argv, &k, tab_tmp, &i);

    if (strncmp("quit", tab_tmp, 4) == 0)
      return (aux(tab_tmp, -1));

    if (exec_str(tab_tmp, cmd, envp) != 0)
      return (aux(tab_tmp, 1));

    free(tab_tmp);
    return (0);
  }
  else
  {
    tab_tmp = aux2(&k, tab_tmp, &i);
    i = exec_str(tab_tmp, cmd, envp);
    free(tab_tmp);
    return (-i - 1);
  }
}
